package com.foreknow.demo14;


import com.mysql.cj.jdbc.ConnectionImpl;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 完成增删改查的方法
 */
public class DBUtil {
    private  Connection statement;
    private  Connection conn;

    /**
     * 增加
     */
    public void insert(){
        try {
           Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/base23?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC","root","123456");
            Statement statement = conn.createStatement();
           ResultSet rs =  statement.executeQuery("SELECT * FROM user");
            List<User> list = new ArrayList<>();
            while(rs.next()){
                int id = rs.getInt("id");//获取第一列的值
                String username = rs.getString("username");//获取到第二列的值
                String password = rs.getString("password");//获取到第三列的值
//                System.out.println(id+"----"+username+"----"+password);
                User user = new User();
                user.setUsername(username);
                user.setPassword(password);
                //将对象保存到集合中
                list.add(user);
            }
            for (User user:list){
                System.out.println(user.getUsername());
            }

            System.out.println("_____________________insert delete update___________");
            int isRigth = statement.executeUpdate("INSERT INTO user(username,password) VALUES('testss','12345')");
            if(isRigth==1){
                System.out.println("dml success......");
                //            rs.clo se();
            statement.close();
            conn.close();
            }else {
                System.out.println("dml error");
            }
            } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除,修改，查找
     */

    public int delete(int id){
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/base23?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC","root","123456");
            Statement statement = conn.createStatement();
            int updat = statement.executeUpdate("DELETE FROM user WHERE id=4;");
            if (updat == 1){
                System.out.println("dml success....");
            }else{
                System.out.println("dml error.....");
            }
            statement.close();
            conn.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return id;
    }


}
